package threads;

import java.util.Random;
import java.util.concurrent.Phaser;

public class PhaserTest {
    static Random r = new Random();
    private static Phaser phaser = new Phaser(7) {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0: {
                    System.out.println("所有人都到齐了" + registeredParties);
                    System.out.println();
                    return false;
                }
                case 1: {
                    System.out.println("所有人都吃完了" + registeredParties);
                    System.out.println();
                    return false;
                }
                case 2: {
                    System.out.println("所有人都离开了" + registeredParties);
                    System.out.println();
                    return false;
                }
                case 3: {
                    System.out.println("新郎新娘入洞房：" + registeredParties);
                    System.out.println();
                    return true;
                }
                default:
                    return true;
            }
        }
    };

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new Person("p" + i)).start();
        }
        new Thread(new Person("新郎")).start();
        new Thread(new Person("新娘")).start();
    }

    static class Person implements Runnable {
        String name;

        public Person(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                arrive();
                eat();
                leave();
                hag();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void arrive() throws InterruptedException {
            Thread.sleep(r.nextInt(1000));
            System.out.println(name + "到达现场");
            phaser.arriveAndAwaitAdvance();
        }

        public void eat() throws InterruptedException {
            Thread.sleep(r.nextInt(1000));
            System.out.println(name + "吃饭了");
            phaser.arriveAndAwaitAdvance();
        }


        public void leave() throws InterruptedException {
            Thread.sleep(r.nextInt(1000));
            System.out.println(name + "离开了");
            phaser.arriveAndAwaitAdvance();
        }

        public void hag() throws InterruptedException {
            if (name.equals("新郎") || "新娘".equals(name)) {
                Thread.sleep(r.nextInt(1000));
                System.out.println(name + "入洞房了");
                phaser.arriveAndAwaitAdvance();
            }
        }
    }
}
